const express = require("express");
const app = express();
const port = 3000;
// 导入cors中间件
const cors = require("cors");
// 导入body-parser中间件
const bodyParser = require("body-parser");
// 全局挂载中间件
// 导入jwt
const jwt = require("./utils/JWT");
// 路由导入
const loginRouter = require("./routes/login");
const userInfoRouter = require("./routes/userInfo");
const companyRouter = require("./routes/company");
const adminRouter = require("./routes/admin");
const productRouter = require("./routes/product");
const messageRouter = require("./routes/message");
const fileRouter = require("./routes/file");
const loginLogRouter = require("./routes/loginLog");
const operationLogRouter = require("./routes/operationLog");
const overviewRouter = require("./routes/overview");
const departmentMsgRouter = require("./routes/departmentMsg");

const multer = require("multer");
const Joi = require("joi");
require("events").EventEmitter.defaultMaxListeners = 100;

// multer 是一个node中间件，用于处理multipart/form-data类型的表单数据
// 主要用于上传文件
const upload = multer({ dest: "./public/upload" });
app.use((req, res, next) => {
  // status = -1为失败，1为成功
  res.cc = (err, status = -1) => {
    res.send({
      status,
      // 判断error是错误对象还是字符串
      message: err instanceof Error ? err.message : err,
    });
  };
  next();
});
app.use(
  cors({
    origin: "http://localhost:8080",
    methods: ["GET", "POST"],
  })
);
app.use(upload.any());
app.use(express.static("./public"));
app.use(jwt.verify);

// extended位false，职位数组或字符串，为true时值可以是任意类型
app.use(bodyParser.urlencoded({ extended: false }));
// 处理json格式
app.use(bodyParser.json());

// 路由使用
app.use("/api", loginRouter);
app.use("/user", userInfoRouter);
app.use("/company", companyRouter);
app.use("/admin", adminRouter);
app.use("/product", productRouter);
app.use("/message", messageRouter);
app.use("/file", fileRouter);
app.use("/loginLog", loginLogRouter);
app.use("/operationLog", operationLogRouter);
app.use("/overview", overviewRouter);
app.use("/departmentMsg", departmentMsgRouter);

// joi验证
app.use((err, req, res, next) => {
  if (err instanceof Joi.ValidationError) {
    return res.send({
      status: -1,
      message: "输入不合规范",
    });
  }
  next();
});

// 监听端口
app.listen(3000, () => {
  console.log(`服务启动成功: http://127.0.0.1:${port}`);
});
